<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Kotlin编程第一课--(Android项目篇)34  Kotlin与Jetpack简直是天生一对！ | 码行</title><meta name="author" content="Carl Su"><meta name="copyright" content="Carl Su"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="今天，我们来聊聊 Android 的 Jetpack。 在我看来，Kotlin 和 Jetpack，它们两个简直就是天生一对。作为 Android 开发者，如果只用 Kotlin 不用 Jetpack，我们其实很难在 Android 平台充分发挥 Kotlin 的语言优势。而如果我们只用 Jetpack 而不用 Kotlin，那么，我们将只能用到 Jetpack 的小部分功能。毕竟，Jetpack">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin编程第一课--(Android项目篇)34  Kotlin与Jetpack简直是天生一对！">
<meta property="og:url" content="https://devsu.top/posts/b63f0842/index.html">
<meta property="og:site_name" content="码行">
<meta property="og:description" content="今天，我们来聊聊 Android 的 Jetpack。 在我看来，Kotlin 和 Jetpack，它们两个简直就是天生一对。作为 Android 开发者，如果只用 Kotlin 不用 Jetpack，我们其实很难在 Android 平台充分发挥 Kotlin 的语言优势。而如果我们只用 Jetpack 而不用 Kotlin，那么，我们将只能用到 Jetpack 的小部分功能。毕竟，Jetpack">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s2.loli.net/2023/03/14/ViqYvHWes9C2f6J.jpg">
<meta property="article:published_time" content="2022-07-02T01:58:04.000Z">
<meta property="article:modified_time" content="2023-03-23T08:02:42.145Z">
<meta property="article:author" content="Carl Su">
<meta property="article:tag" content="Kotlin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s2.loli.net/2023/03/14/ViqYvHWes9C2f6J.jpg"><link rel="shortcut icon" href="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"><link rel="canonical" href="https://devsu.top/posts/b63f0842/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6243425e2ecb037931274c4ca1db3132";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Carl Su","link":"链接: ","source":"来源: 码行","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Kotlin编程第一课--(Android项目篇)34  Kotlin与Jetpack简直是天生一对！',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-23 16:02:42'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s2.loli.net/2023/03/09/QrI9mgJ4XlbEPzN.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">169</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">37</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">38</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('https://s2.loli.net/2023/03/14/ViqYvHWes9C2f6J.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="码行"><img class="site-icon" src="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"/><span class="site-name">码行</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Kotlin编程第一课--(Android项目篇)34  Kotlin与Jetpack简直是天生一对！</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-07-02T01:58:04.000Z" title="发表于 2022-07-02 09:58:04">2022-07-02</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-23T08:02:42.145Z" title="更新于 2023-03-23 16:02:42">2023-03-23</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/">Android</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/">Kotlin</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/Kotlin%E7%BC%96%E7%A8%8B%E7%AC%AC%E4%B8%80%E8%AF%BE/">Kotlin编程第一课</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Kotlin编程第一课--(Android项目篇)34  Kotlin与Jetpack简直是天生一对！"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>今天，我们来聊聊 Android 的 Jetpack。</p>
<p>在我看来，Kotlin 和 Jetpack，它们两个简直就是天生一对。作为 Android 开发者，如果只用 Kotlin 不用 Jetpack，我们其实很难在 Android 平台充分发挥 Kotlin 的语言优势。而如果我们只用 Jetpack 而不用 Kotlin，那么，我们将只能用到 Jetpack 的小部分功能。毕竟，Jetpack 当中有很多 API 和库，是专门为 Kotlin 提供的。</p>
<p>经过前面课程内容的学习，相信现在你已经对 Kotlin 十分熟悉了，那么，接下来就让我们来看看 Jetpack 吧！这节课里，我会为你介绍 Jetpack 核心库的基本概念、简单用法，以及它跟 Kotlin 之间的关系，从而也为我们下节课的实战项目打下基础。</p>
<h2 id="Jetpack-简介"><a href="#Jetpack-简介" class="headerlink" title="Jetpack 简介"></a>Jetpack 简介</h2><p>Jetpack，它有“喷气式背包”的意思。对于我们开发者来说，它其实就是 Google 官方为我们提供的一套开发套件，专门用来帮助 Android 开发者提升开发效率、提升应用稳定性的。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/ba/c2/ba1e45560e1e6510591d75ee6ee862c2.jpg?wh=600x600" alt="img"></p>
<p>Android Jetpack，最初的宣传图标，就是“穿着喷气式背包的 Android 机器人”。大概意思就是：有了 Jetpack，Android 就能“起飞了”。这当然只是一种夸张的比喻，不过，从我实际的开发体验来说，Jetpack 确实可以给 Android 开发者带来极大的好处，尤其是当 Jetpack 与 Kotlin 结合到一起的情况下。</p>
<p>我们先来了解下 KTX。</p>
<h2 id="KTX"><a href="#KTX" class="headerlink" title="KTX"></a>KTX</h2><p>KTX 是 Jetpack 当中最特殊的一类库，它是由 Kotlin 编写的，同时也仅为 Kotlin 开发者服务，使用 Java 语言的 Android 开发者是用不了的。KTX，它的作用其实是对当前 Android 生态当中的 API 进行额外补充。它依托 Kotlin 的扩展能力，为 Android 原有 API 增加新的：扩展函数、扩展属性、高阶函数、命名参数、参数默认值、协程支持。</p>
<p>如果我们想要使用 KTX 的核心功能，我们需要单独进行依赖：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段1</span></span><br><span class="line"></span><br><span class="line">dependencies &#123;</span><br><span class="line">    implementation <span class="string">&quot;androidx.core:core-ktx:1.7.0&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>让我们来看一个关于 SharedPreference 的简单例子，如果我们使用 Java，我们大概率是需要写一堆模板代码的，类似这样：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段2</span></span><br><span class="line"></span><br><span class="line">SharedPreferences sharedPreferences= getSharedPreferences(<span class="string">&quot;data&quot;</span>,Context.MODE_PRIVATE);</span><br><span class="line">SharedPreferences.Editor editor = sharedPreferences.edit();</span><br><span class="line">editor.putString(SP_KEY_RESPONSE, response);</span><br><span class="line"></span><br><span class="line">editor.commit();</span><br><span class="line">editor.apply();</span><br></pre></td></tr></table></figure>

<p>不过，如果我们有了 KTX，那么代码就会变得极其简单：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段3</span></span><br><span class="line"></span><br><span class="line">preference.edit &#123; putBoolean(<span class="string">&quot;key&quot;</span>, value) &#125;</span><br></pre></td></tr></table></figure>

<p>上面的这个 edit() 方法，其实是一个高阶函数，它是由 KTX 提供的，如果你去看它的源代码，会发现，它其实就是一个扩展出来的高阶函数：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段4</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">inline</span> <span class="function"><span class="keyword">fun</span> SharedPreferences.<span class="title">edit</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">        commit: <span class="type">Boolean</span> = <span class="literal">false</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">        action: <span class="type">SharedPreferences</span>.<span class="type">Editor</span>.() -&gt; <span class="type">Unit</span></span></span></span><br><span class="line"><span class="params"><span class="function">)</span></span> &#123;</span><br><span class="line">    <span class="keyword">val</span> editor = edit()</span><br><span class="line">    action(editor)</span><br><span class="line">    <span class="keyword">if</span> (commit) &#123;</span><br><span class="line">        editor.commit()</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        editor.apply()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，KTX 其实就是将一些常见的模板代码封装了起来，然后以扩展函数的形式提供给开发者。虽然它自身的原理很简单，但是却可以大大提升开发者的效率。</p>
<p>KTX 除了能够扩展 Android SDK 的 API 以外，它还可以扩展 Jetpack 当中其他的库，比如说 LiveData、Room 等等。接下来，我们就来看看 Jetpack 当中比较核心的库：Lifecycle。</p>
<h2 id="Lifecycle"><a href="#Lifecycle" class="headerlink" title="Lifecycle"></a>Lifecycle</h2><p>Lifecycle，其实就是 Android 的生命周期组件。在整个 Jetpack 组件当中的地位非常特殊，是必学的组件。举个例子，其他的组件比如 WorkManager，如果我们实际工作中用不上，那么我们不去学它是不会有什么问题的。Lifecycle 不一样，只要我们是做 Android 开发的，我们就绕不开 Lifecycle。Activity 里面有 Lifecycle；Fragment 里面也有；LiveData 里面也有；</p>
<p>ViewModel 底层也用到了 Lifecycle；使用协程也离不开 Lifecycle。</p>
<p>那么，Lifecycle 到底是什么呢？我们平时提到生命周期，往往都是说的 Activity、Fragment，而它们两者之间却有一个很大的问题，<strong>生命周期函数不一致</strong>。</p>
<p>Activity 的生命周期我们肯定心里有数，不过 Fragment 生命周期函数比 Activity 多了几个：onCreateView、onViewCreated、onViewStateRestore、onDestoryView。最重要的是，Fragment 生命周期、回调函数、Fragment 内部 View 的生命周期，它们三者之间还有很复杂的对应关系。换句话说，Fragment 的生命周期函数要比 Activity 复杂一些。</p>
<p>加之，Activity 和 Fragment 结合的情况下，它们的生命周期行为在不同版本的 Android 系统上行为可能还会不一致。这在某些边界条件下，还会引发一些难以排查的 bug，进一步增加我们 Android 程序员的维护成本。</p>
<p>在计算机世界里，大部分问题都可以通过增加一个抽象层来解决。Android 团队的做法就是推出了 Lifecycle 这个架构组件，用它来统一 Activity、Fragment 的生命周期行为。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/f0/a1/f03yy1b87813c58f5591aab720e432a1.jpg?wh=2000x904" alt="img"></p>
<p>有了 LifeCycle 以后，我们开发者就可以面向 Lifecycle 编程。比如说，我们希望实现一个通用的地理位置监听的 Manager，就可以这样来做：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段5</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 不关心调用方是Activity还是Fragment</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">LocationManager</span>(</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> context: Context,</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> callback: (Location) -&gt; <span class="built_in">Unit</span></span><br><span class="line">): DefaultLifecycleObserver &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onStart</span><span class="params">(owner: <span class="type">LifecycleOwner</span>)</span></span> &#123;</span><br><span class="line">        start()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onStop</span><span class="params">(owner: <span class="type">LifecycleOwner</span>)</span></span> &#123;</span><br><span class="line">        stop()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">start</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="comment">// 使用高德之类的 SDK 请求地理位置</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">stop</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="comment">// 停止</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">LifecycleExampleActivity</span> : <span class="type">AppCompatActivity</span>() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreate</span><span class="params">(savedInstanceState: <span class="type">Bundle</span>?)</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState)</span><br><span class="line">        setContentView(R.layout.activity_life_cycle_example)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">val</span> locationManager = LocationManager(<span class="keyword">this</span>) &#123;</span><br><span class="line">            <span class="comment">// 展示地理位置信息</span></span><br><span class="line">        &#125;</span><br><span class="line">        lifecycle.addObserver(locationManager)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面代码的 LocationManager 只需要实现 DefaultLifecycleObserver 这个接口即可，外部是在 Activity 还是在 Fragment 当中使用，根本不必关心。</p>
<h2 id="Lifecycle-与协程"><a href="#Lifecycle-与协程" class="headerlink" title="Lifecycle 与协程"></a>Lifecycle 与协程</h2><p>通过前面课程的学习，我们知道，协程其实也是有生命周期的。也就是说，Android 和 Kotlin 协程都是有生命周期的。这就意味着，当我们在 Android 当中使用协程的时候，就要格外小心。</p>
<p>作为 Android 开发者，你一定知道内存泄漏的概念：当内存变量的生命周期大于 Android 生命周期的时候，我们就认为内存发生泄漏了。类似的，当协程的生命周期大于 Android 生命周期的时候，<strong>协程也就发生泄漏了</strong>。</p>
<p>这一点，Android 官方早就帮我们考虑到了。Lifecycle 还可以跟我们前面提到的 KTX 结合到一起，进一步为 Kotlin 协程提供支持。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/ba/5c/ba1d19579cd0e6e6a8e4e004732c705c.png?wh=884x456" alt="img"></p>
<p>在 Activity、Fragment 当中，KTX 还提供了对应的 lifecycleScope，它本质上就是一个：与生命周期绑定的协程作用域。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段6</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">val</span> LifecycleOwner.lifecycleScope: LifecycleCoroutineScope</span><br><span class="line">    <span class="comment">// 2</span></span><br><span class="line">    <span class="keyword">get</span>() = lifecycle.coroutineScope</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">LifecycleCoroutineScope</span> <span class="keyword">internal</span> <span class="keyword">constructor</span>() : CoroutineScope &#123;</span><br><span class="line">    <span class="keyword">internal</span> <span class="keyword">abstract</span> <span class="keyword">val</span> lifecycle: Lifecycle</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> <span class="title">launchWhenCreated</span><span class="params">(block: <span class="type">suspend</span> <span class="type">CoroutineScope</span>.() -&gt; <span class="type">Unit</span>)</span></span>: Job = launch &#123;</span><br><span class="line">        lifecycle.whenCreated(block)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> <span class="title">launchWhenStarted</span><span class="params">(block: <span class="type">suspend</span> <span class="type">CoroutineScope</span>.() -&gt; <span class="type">Unit</span>)</span></span>: Job = launch &#123;</span><br><span class="line">        lifecycle.whenStarted(block)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> <span class="title">launchWhenResumed</span><span class="params">(block: <span class="type">suspend</span> <span class="type">CoroutineScope</span>.() -&gt; <span class="type">Unit</span>)</span></span>: Job = launch &#123;</span><br><span class="line">        lifecycle.whenResumed(block)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 Android 当中，Activity 和 Fragment 都会实现 LifecycleOwner 这个接口，代表它们都是拥有生命周期的组件。注释 1 处，这里使用了 Kotlin 的扩展属性，为 LifecycleOwner 扩展了 lifecycleScope。它的类型是 LifecycleCoroutineScope，而它其实就是 CoroutineScope 的实现类。</p>
<p>lifecycleScope 这个属性的具体实现，其实是通过注释 2 处的自定义 getter() 实现的，也就是：Lifecycle.coroutineScope。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段7</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">val</span> Lifecycle.coroutineScope: LifecycleCoroutineScope</span><br><span class="line">    <span class="keyword">get</span>() &#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">            <span class="comment">// 1</span></span><br><span class="line">            <span class="keyword">val</span> existing = mInternalScopeRef.<span class="keyword">get</span>() <span class="keyword">as</span> LifecycleCoroutineScopeImpl?</span><br><span class="line">            <span class="keyword">if</span> (existing != <span class="literal">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> existing</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 2</span></span><br><span class="line">            <span class="keyword">val</span> newScope = LifecycleCoroutineScopeImpl(</span><br><span class="line">                <span class="keyword">this</span>,</span><br><span class="line">                SupervisorJob() + Dispatchers.Main.immediate</span><br><span class="line">            )</span><br><span class="line">            <span class="comment">//3</span></span><br><span class="line">            <span class="keyword">if</span> (mInternalScopeRef.compareAndSet(<span class="literal">null</span>, newScope)) &#123;</span><br><span class="line">                newScope.register()</span><br><span class="line">                <span class="keyword">return</span> newScope</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，Lifecycle.coroutineScope 仍然是一个扩展属性。它的逻辑其实也很简单，主要是分为了三个步骤：</p>
<ul>
<li>第一步，检查是否存在缓存的 CoroutineScope，如果存在，那就直接返回即可。</li>
<li>第二步，如果不存在缓存，那就创建一个新的协程作用域。在创建的作用域的时候，用到了两个我们熟悉的概念：SupervisorJob、Dispatchers.Main，它们都是协程上下文的元素，<strong>前者是用来隔离协程异常传播的，后者是指定协程执行线程的</strong>。</li>
<li>第三步，更新缓存，并且调用 register() 绑定 scope 与 Lifecycle 的关系，最后返回</li>
</ul>
<p>接下来，我们打破砂锅问到底，看看 register() 的具体逻辑是什么：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">internal</span> <span class="keyword">class</span> <span class="title class_">LifecycleCoroutineScopeImpl</span>(</span><br><span class="line">    <span class="keyword">override</span> <span class="keyword">val</span> lifecycle: Lifecycle,</span><br><span class="line">    <span class="keyword">override</span> <span class="keyword">val</span> coroutineContext: CoroutineContext</span><br><span class="line">    <span class="comment">// 2</span></span><br><span class="line">) : LifecycleCoroutineScope(), LifecycleEventObserver &#123;</span><br><span class="line">    <span class="keyword">init</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (lifecycle.currentState == Lifecycle.State.DESTROYED) &#123;</span><br><span class="line">            coroutineContext.cancel()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 1</span></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">register</span><span class="params">()</span></span> &#123;</span><br><span class="line">        launch(Dispatchers.Main.immediate) &#123;</span><br><span class="line">            <span class="keyword">if</span> (lifecycle.currentState &gt;= Lifecycle.State.INITIALIZED) &#123;</span><br><span class="line">                lifecycle.addObserver(<span class="keyword">this</span><span class="symbol">@LifecycleCoroutineScopeImpl</span>)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                coroutineContext.cancel()</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3</span></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onStateChanged</span><span class="params">(source: <span class="type">LifecycleOwner</span>, event: <span class="type">Lifecycle</span>.<span class="type">Event</span>)</span></span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (lifecycle.currentState &lt;= Lifecycle.State.DESTROYED) &#123;</span><br><span class="line">            lifecycle.removeObserver(<span class="keyword">this</span>)</span><br><span class="line">            coroutineContext.cancel()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">LifecycleEventObserver</span> <span class="title">extends</span> <span class="title">LifecycleObserver</span> &#123;</span><br><span class="line">    void onStateChanged(<span class="meta">@NonNull</span> LifecycleOwner source, <span class="meta">@NonNull</span> Lifecycle.Event event);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的代码一共有三个注释，我们一个个来看：</p>
<ul>
<li>注释 1，register()，可以看到，它的逻辑其实很简单，主要就是调用了 addObserver()，将自身作为观察者传了进去。之所以可以这么做，还是因为注释 2 处的 LifecycleEventObserver。</li>
<li>注释 2，LifecycleEventObserver，它其实就是一个 SAM 接口，每当 LifeCycleOwner 的生命周期发生变化的时候，这个 onStateChanged() 方法就会被调用。而这个方法的具体实现则在注释 3 处。</li>
<li>注释 3，这里的逻辑也很简单，当 LifeCycleOwner 对应的 Activity、Fragment 被销毁以后，就会调用 removeObserver(this) 移除观察者，最后，就是最关键的 coroutineContext.cancel()，取消整个作用域里所有的协程任务。</li>
</ul>
<p>这样一来，就能保证 LifeCycle 与协程的生命周期完全一致了，也就不会出现协程泄漏的问题了。</p>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>这节课，我们主要了解了 Android 当中的 Jetpack，它是 Android 官方提供给开发者的一个开发套件，可以帮助我们开发者提升开发效率。Jetpack 当中其实有几十个库，在这节课里，我们是着重讲解了其中的 KTX 与 LifeCycle。</p>
<ul>
<li><p><strong>KTX</strong>，主要是依托 Kotlin 的扩展能力，为 Android 原有 API 增加新的：扩展函数、扩展属性、高阶函数、命名参数、参数默认值、协程支持。</p>
</li>
<li><p><strong>Lifecycle</strong>，其实就是 Android 的生命周期组件。它统一封装了 Activity、Fragment 等 Android 生命周期的组件。让我们开发者可以只关注 LifeCycle 的生命周期，而不用在意其他细节。</p>
</li>
<li><p><strong>KTX 还为 LifeCycle 增加了协程支持，也就是 lifecycleScope</strong>。在它的底层，这个协程作用域和宿主的生命周期进行了绑定。当宿主被销毁以后，它可以确保 lifecycleScope 当中的协程任务，也跟着被取消。</p>
</li>
</ul>
<p>所以，对于 Android 开发者来说，Kotlin 和 Jetpack 是一个“你中有我，我中有你”的关系，我们把它们称为“天生一对”一点儿也不为过。</p>
<h2 id="思考题"><a href="#思考题" class="headerlink" title="思考题"></a>思考题</h2><p>在 Android 中使用协程的时候，除了 lifecycleScope 以外，我们还经常会使用 ViewModel 的 viewModelScope。你能结合前面协程篇、源码篇的知识点，分析出 viewModelScope 的实现原理吗？</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyViewModel</span> : <span class="type">ViewModel</span>() &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> _persons: MutableLiveData&lt;List&lt;Person&gt;&gt; = MutableLiveData()</span><br><span class="line">    <span class="keyword">val</span> persons: LiveData&lt;List&lt;Person&gt;&gt; = _persons</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">loadPersons</span><span class="params">()</span></span> &#123;</span><br><span class="line">        viewModelScope.launch &#123;</span><br><span class="line">            delay(<span class="number">500L</span>)</span><br><span class="line">            _persons.value = listOf(Person(<span class="string">&quot;Tom&quot;</span>), Person(<span class="string">&quot;Jack&quot;</span>))</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 扩展属性</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">val</span> ViewModel.viewModelScope: CoroutineScope</span><br><span class="line">    <span class="keyword">get</span>() &#123;</span><br><span class="line">        <span class="keyword">val</span> scope: CoroutineScope? = <span class="keyword">this</span>.getTag(JOB_KEY)</span><br><span class="line">        <span class="keyword">if</span> (scope != <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> scope</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> setTagIfAbsent(</span><br><span class="line">            JOB_KEY,</span><br><span class="line">            <span class="comment">// 实现类</span></span><br><span class="line">            CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 实现了Closeable的CoroutineScope</span></span><br><span class="line"><span class="keyword">internal</span> <span class="keyword">class</span> <span class="title class_">CloseableCoroutineScope</span>(context: CoroutineContext) : Closeable, CoroutineScope &#123;</span><br><span class="line">    <span class="keyword">override</span> <span class="keyword">val</span> coroutineContext: CoroutineContext = context</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">close</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="comment">// 取消</span></span><br><span class="line">        coroutineContext.cancel()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">ViewModel</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Nullable</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, Object&gt; mBagOfTags = new HashMap&lt;&gt;();</span><br><span class="line">    <span class="keyword">private</span> volatile boolean mCleared = <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@SuppressWarnings(<span class="string">&quot;WeakerAccess&quot;</span>)</span></span><br><span class="line">    <span class="keyword">protected</span> void onCleared() &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@MainThread</span></span><br><span class="line">    <span class="keyword">final</span> void clear() &#123;</span><br><span class="line">        mCleared = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (mBagOfTags != <span class="literal">null</span>) &#123;</span><br><span class="line">            synchronized (mBagOfTags) &#123;</span><br><span class="line">                <span class="keyword">for</span> (Object value : mBagOfTags.values()) &#123;</span><br><span class="line">                    <span class="comment">// 调用scope的close()</span></span><br><span class="line">                    closeWithRuntimeException(value);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        onCleared();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// scope暂存起来</span></span><br><span class="line">    <span class="meta">@SuppressWarnings(<span class="string">&quot;unchecked&quot;</span>)</span></span><br><span class="line">    &lt;T&gt; T setTagIfAbsent(String key, T newValue) &#123;</span><br><span class="line">        T previous;</span><br><span class="line">        synchronized (mBagOfTags) &#123;</span><br><span class="line">            previous = (T) mBagOfTags.<span class="keyword">get</span>(key);</span><br><span class="line">            <span class="keyword">if</span> (previous == <span class="literal">null</span>) &#123;</span><br><span class="line">                mBagOfTags.put(key, newValue);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        T result = previous == <span class="literal">null</span> ? newValue : previous;</span><br><span class="line">        <span class="keyword">if</span> (mCleared) &#123;</span><br><span class="line"></span><br><span class="line">            closeWithRuntimeException(result);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> static void closeWithRuntimeException(Object obj) &#123;</span><br><span class="line">        <span class="keyword">if</span> (obj instanceof Closeable) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                ((Closeable) obj).close();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                <span class="keyword">throw</span> new RuntimeException(e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://devsu.top">Carl Su</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://devsu.top/posts/b63f0842/">https://devsu.top/posts/b63f0842/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://devsu.top" target="_blank">码行</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Kotlin/">Kotlin</a></div><div class="post_share"><div class="social-share" data-image="https://s2.loli.net/2023/03/14/ViqYvHWes9C2f6J.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/58999c28/" title="Kotlin编程第一课--(Android项目篇)35  用Kotlin写一个GitHub Trending App"><img class="cover" src="https://www.gaoguang.com/uploads/allimg/201015/2-201015120J1.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Kotlin编程第一课--(Android项目篇)35  用Kotlin写一个GitHub Trending App</div></div></a></div><div class="next-post pull-right"><a href="/posts/11a43e5b/" title="Kotlin编程第一课--(Android项目篇)33 Java Android开发者还会有未来吗？"><img class="cover" src="https://img2.baidu.com/it/u=2147165840,2215518645&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=500&amp;h=889" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Kotlin编程第一课--(Android项目篇)33 Java Android开发者还会有未来吗？</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/85d82fa8/" title="Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？"><img class="cover" src="https://static001.geekbang.org/resource/image/b6/1c/b65feyy0bdc4764c6564a95912d7851c.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-06</div><div class="title">Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？</div></div></a></div><div><a href="/posts/be9f17d6/" title="Kotlin编程第一课(目录)"><img class="cover" src="https://img2.baidu.com/it/u=3956021957,3313212296&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-10</div><div class="title">Kotlin编程第一课(目录)</div></div></a></div><div><a href="/posts/83a7144c/" title="2023-01-17-Kotlin协程 -  结构化并发"><img class="cover" src="https://s2.loli.net/2023/03/14/xEyFgn24zZPXe15.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-17</div><div class="title">2023-01-17-Kotlin协程 -  结构化并发</div></div></a></div><div><a href="/posts/68bf7d20/" title="Kotlin函数"><img class="cover" src="https://img1.baidu.com/it/u=1546227440,2897989905&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin函数</div></div></a></div><div><a href="/posts/a20c9e06/" title="Kotlin协程"><img class="cover" src="https://s2.loli.net/2023/03/14/3MHPBy1Q4GncRlF.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-09</div><div class="title">Kotlin协程</div></div></a></div><div><a href="/posts/8c331668/" title="Kotlin内置函数apply、let、run、with、also等区别"><img class="cover" src="https://s2.loli.net/2023/03/14/OpxWcuy2ktMzoQD.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin内置函数apply、let、run、with、also等区别</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div><div id="comment-switch"><span class="first-comment">Valine</span><span class="switch-btn"></span><span class="second-comment">Disqus</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div><div><div id="disqus_thread"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Jetpack-%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">Jetpack 简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#KTX"><span class="toc-number">2.</span> <span class="toc-text">KTX</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lifecycle"><span class="toc-number">3.</span> <span class="toc-text">Lifecycle</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lifecycle-%E4%B8%8E%E5%8D%8F%E7%A8%8B"><span class="toc-number">4.</span> <span class="toc-text">Lifecycle 与协程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-number">5.</span> <span class="toc-text">小结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%9D%E8%80%83%E9%A2%98"><span class="toc-number">6.</span> <span class="toc-text">思考题</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By Carl Su</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">学无止境</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script>function loadDisqus () {
  var disqus_config = function () {
    this.page.url = 'https://devsu.top/posts/b63f0842/'
    this.page.identifier = '/posts/b63f0842/'
    this.page.title = 'Kotlin编程第一课--(Android项目篇)34  Kotlin与Jetpack简直是天生一对！'
  };

  window.disqusReset = () => {
    DISQUS.reset({
      reload: true,
      config: disqus_config
    })
  }

  if (window.DISQUS) disqusReset()
  else {
    (function() { 
      var d = document, s = d.createElement('script');
      s.src = 'https://.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
    })();
  }

  document.getElementById('darkmode').addEventListener('click', () => {
    setTimeout(() => window.disqusReset(), 200)
  })
}

if ('Valine' === 'Disqus' || !true) {
  if (true) btf.loadComment(document.getElementById('disqus_thread'), loadDisqus)
  else loadDisqus()
} else {
  function loadOtherComment () {
    loadDisqus()
  }
}
</script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>